package com.yimaxiaoerlang.module_signalling.core;

import android.util.Log;

import java.net.URI;
import java.net.URISyntaxException;

public class YMSocketManager implements YMIEvent {
    private String SOCKET_URL = "wss://im.yimaxiaoerlang.cn/signal";

    public void setSOCKET_URL(String SOCKET_URL) {
        if (SOCKET_URL == null) return;
        this.SOCKET_URL = SOCKET_URL;
    }

    private YMRtmWebSocketClient webSocket;
    private YMKEvent kEvent;
    private String nowToken = "";

    public void connect(String token) {

        if (webSocket != null&&nowToken.equals(token) && webSocket.isOpen()) {
            return;
        }
        if (webSocket != null&&webSocket.isOpen()) {
            unConnect();
        }
        if (webSocket == null) {
            URI uri = null;
            try {
                uri = new URI(SOCKET_URL);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            webSocket = new YMRtmWebSocketClient(uri, this);
        }

        nowToken = token;
        Log.e("zhaoxiaoting", "webSocket==============================="+webSocket);
        Log.e("zhaoxiaoting", "token==============================="+token);
        webSocket.addHeader("Sec-WebSocket-Protocol", token);
        webSocket.connect();

    }

    public void sendMessage(String msg) {
        if (webSocket != null && webSocket.isOpen()) {
            webSocket.send(msg);
        } else {
            Log.e("webSocket", "webSocket is null or webSocket is close");
        }
    }

    public void unConnect() {
        if (webSocket != null) {
            webSocket.setConnectFlag(false);
            webSocket.close();
            webSocket = null;
        }
    }

    @Override
    public void onConnect() {
        if (kEvent != null) {
            kEvent.onConnect();
        }
    }

    @Override
    public void onDisconnect() {
        if (kEvent != null) {
            kEvent.onDisconnect();
        }
    }

    @Override
    public void onMessage(String msg) {
        if (kEvent != null) {
            kEvent.onMessage(msg);
        }
    }

    @Override
    public void reConnect() {
        if (kEvent != null) {
            kEvent.reConnect();
        }
    }

    public void setkEvent(YMKEvent kEvent) {
        this.kEvent = kEvent;
    }
}
